package com.jdz.interceptor;

import com.google.gson.Gson;
import com.jdz.common.Const;
import com.jdz.common.ResponseCode;
import com.jdz.common.ServerResponse;
import com.jdz.service.IUserService;
import com.jdz.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;

public class AuthorityInterceptor implements HandlerInterceptor {
    @Autowired
    IUserService iUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        //获取请求的url
        String url = request.getRequestURL().toString();
        //判断url是否是公开 地址（实际使用时将公开 地址配置配置文件中）//这里公开地址是登陆提交的地址if(url.indexOf("login.action")>=0){
        //如果进行登陆提交，放行returntrue;

        HttpSession session = request.getSession();
        response.setHeader("Content-Type","application/json;charset=UTF-8");

        UserVo userVo = (UserVo) session.getAttribute(Const.CURRENT_USER);
        Gson gson = new Gson();
        PrintWriter out = null ;
        String json = gson.toJson(ServerResponse.createByErrorMessage("无权限操作,需要管理员权限"));
        if (iUserService.checkAdminRole(userVo).isSuccess()) {
            //是管理员
            if (iUserService.checkPrivilege(userVo, url).isSuccess()) {
                return true;
            } else {
                out = response.getWriter();
                out.append(json);
                out.close();
                return false;
            }
        } else {
            out = response.getWriter();
            out.append(json);
            out.close();
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
